package com.appology.users;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

public abstract class ChuckUserHelper {

	private static Query query;
	private static DatastoreService datastore;
	private static Entity user;
	private static ChuckUser chuckUser;

	/**
	 * This method accepts a googleId string and attempts to fetch the
	 * corresponding ChuckUsere from the datastore. If one cannot be found, then
	 * it returns null.
	 * 
	 * @param googleId
	 * @return ChuckUser
	 */
	public static ChuckUser getChuckUserByGoogleId(String googleId) {

		// Get a DatastoreService to pull queries from
		datastore = DatastoreServiceFactory.getDatastoreService();

		// Create a new query on the "ChuckUser" entity type
		query = new Query(ChuckUser.ENTITY_TYPE);

		// Add a filter for the googleId column using the supplied googleId
		query.addFilter(ChuckUser.COLUMN_GOOGLE_ID, Query.FilterOperator.EQUAL,
				googleId);

		// fetch the user and deposit it into an entity that we can read later.
		user = datastore.prepare(query).asSingleEntity();

		// If no entity was returned, then set chuckUser to null
		if (user == null) {
			chuckUser = null;
		} else {

			// Instantiate our ChuckUser using the properties pulled from the
			// Entity returned from the Query
			chuckUser = new ChuckUser(
					(String) user.getProperty(ChuckUser.COLUMN_GOOGLE_ID),
					(String) user.getProperty(ChuckUser.COLUMN_BUZZ_ID),
					(String) user.getProperty(ChuckUser.COLUMN_DISPLAY_NAME));

		}

		// Return chuckUser whether it be null or our newly created ChuckUser
		return chuckUser;
	}
}
